import { useCallback } from "react";
import { onAddAndDelType } from "./components/ColumnAddDel";
import { ITableProps } from ".";

/**
 * @param dataSource 数据引用
 * @param onTableChange 外部传入的change事件
 * @param defaultRowKey 默认rowKey配置
 * @param options 增减行相关配置
 * @returns 增减相关方法
 */
export const useAddAndDel = (
    dataSource: any,
    onTableChange?: ITableProps["onTableChange"],
    defaultRowKey?: string,
    addCallback?: Function,
    delCallback?: Function
) => {
    const onAddAndDelFn = useCallback<onAddAndDelType>(
        (type: "add" | "del" | "delAll", i: number) => {
            let newDataSource = dataSource?.slice?.() || [];
            let newRecord = {};
            if (defaultRowKey) {
                newRecord = { [defaultRowKey]: +Date.now() };
            }
            if (type === "add") {
                newDataSource.splice(i + 1, 0, newRecord);
                if (addCallback) addCallback(newDataSource);
            }
            if (type === "del") {
                newDataSource.splice(i, 1);
                if (delCallback) delCallback(newDataSource);
            }
            if (type === "delAll") {
                newDataSource = [];
            }
            onTableChange &&
                onTableChange(newDataSource, dataSource, {
                    type,
                    currentIndex: i,
                });
        },
        [addCallback, dataSource, defaultRowKey, delCallback, onTableChange]
    );
    return onAddAndDelFn;
};
